<?php

namespace App\HttpController\Api\Device;

use App\Lib\Utils;
use EasySwoole\Component\Di;
use EasySwoole\Http\Message\Status;
use EasySwoole\FastCache\Cache;

use App\Model\Device\DeviceModel as DeviceModel;
use App\Model\Device\DeviceInfoModel as InfoModel;
use App\Model\Device\DeviceLogModel as LogModel;

use EasySwoole\Component\Timer;
use App\Lib\Curl;
use App\HttpController\FormatSubData;

class Online extends \App\HttpController\Api\ApiBase
{

    public function index()
    {
        try {
            $deviceObj = new DeviceModel();
            $infoObj = new InfoModel();
            $logObj = new LogModel();

            $getData = $this->raw;
            $actData = json_decode(Utils::characet($getData), true);
            $sIP = $this->ip;
            $sPort = $this->port;

            if (!isset($actData['Name']) || ($actData['Name'] != 'heartbeatRequest')) {

                $data['name'] = $actData['Name'];
                $data['device_id'] = $sIP.'-'.$actData['DeviceId'];
                $data['device_uuid'] = $sIP.'-'.$actData['UUID'];
                $data['device_mac'] = $sIP.'-'.$actData['Data']['DeviceInfo']['DeviceMAC'];
                $data['remark'] = '非法数据包攻击, 操作标识name为空. IP:'.$sIP;
                $data['create_time'] = time();

                $logObj->add($data);
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
            }

            $di = isset($actData['Data']['DeviceInfo']) ? $actData['Data']['DeviceInfo'] : [];

            $retArray = [];
            $retArray['Name'] = 'heartbeatResponse';
            $retArray['TimeStamp'] = time();
            $retArray['Code'] = 1;
            $retArray['Message'] = 'ok';
            $retArray['EventCount'] = 0;

            $DeviceId = "";
            $DeviceUUID = "";

            if (isset($di['DeviceId'])) {
                $DeviceId = trim(str_replace(array("\r\n", "\r", "\n"), "", $di['DeviceId']));
            }

            if (isset($di['DeviceUUID']) ){
                $DeviceUUID = trim(str_replace(array("\r\n", "\r", "\n"), "", $di['DeviceUUID']));
            }

            if (empty($DeviceUUID)) {

                $data['name'] = $actData['Name'];
                $deviceid = $sIP.'-';
                $data['device_uuid'] = '---';
                $data['device_mac'] = '---';
                $data['remark'] = 'register 非法数据包,device_uuid，IP：'.$sIP;
                $data['create_time'] = time();
                $logObj->add($data);

                $retArray['code'] = 0;
                $retArray['Message'] = 'DeviceUUID为空';
                $retArray['result'] = 251;
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
            }


            if (empty($DeviceId)) {

                $data['name'] = $actData['Name'];
                $deviceid = $sIP.'-';
                $data['device_uuid'] = '---';
                $data['device_mac'] = '---';
                $data['remark'] = 'register 非法数据包,device_id为空，IP：'.$sIP;
                $data['create_time'] = time();
                $logObj->add($data);

                $retArray['code'] = 0;
                $retArray['Message'] = 'DeviceID为空';
                $retArray['result'] = 251;
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
            }

            $dev_where['A.device_uuid'] = $DeviceUUID;
            $deviceInfo = $deviceObj->getDeviceInfo('*', $dev_where);

            if (!$deviceInfo || !is_array($deviceInfo)) {

                $data['name'] = $actData['Name'];
                $deviceid = $sIP.'-';
                $data['device_uuid'] = '---';
                $data['device_mac'] = '---';
                $data['remark'] = 'register 非法数据包,设备唯一码不存在，IP：'.$sIP;
                $data['create_time'] = time();
                $logObj->add($data);

                $retArray['code'] = 0;
                $retArray['Message'] = '设备唯一码不存在';
                $retArray['result'] = 251;
                return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
            }

            $strSession = $DeviceUUID.'_'.$retArray['TimeStamp'];

            $data['deviceid'] = $DeviceId;
            $data['device_uuid'] = $DeviceUUID;
            $data['session'] = $strSession;

            // 第一次注册时间
            if (($deviceInfo['online_time']==NULL) || ($deviceInfo['online_time'] < 10000)) $info['onlinetime'] = $retArray['TimeStamp'];

            // 最后一次登录时间
            $data['last_login_time'] = $retArray['TimeStamp'];

            // 局域网IP, 及定义为局域网设备则更新设备地址
            if (Utils::isIP($sIP) && $deviceInfo['iswan'] == 0) {
                $data['ip'] = $sIP;
                $data['port'] = $sPort;
            }

            if (isset($actData['TimeStamp'])) {
                $data['timestamp'] = $actData['TimeStamp'];
            }

            if (isset($di['DeviceIp'])) {
                $data['ip'] = $di['DeviceIp'];
            }

            if (isset($di['DeviceMac'])) {
                $info['devicemac'] = $di['DeviceMac'];
            }

            if (isset($actData['Data']['HTTPVersion'])) {
                $data['http_version'] = $actData['Data']['HTTPVersion'];
            }

            if (isset($actData['Data']['HeartbeatCount'])) {
                $data['heartbeat_count'] = $actData['Data']['HeartbeatCount'];
            }

            if (isset($actData['Data']['CaptureCount'])) {
                $data['capture_count'] = $actData['Data']['CaptureCount'];
            }

            if (isset($di['WebVersion'])) {
                $data['web_version'] = $di['WebVersion'];
            }

            if (isset($di['CoreVersion'])) {
                $data['core_version'] = $di['CoreVersion'];
            }

            if (isset($di['VersionDate'])) {
                $data['version_date'] = $di['VersionDate'];
            }

            // 心跳间隔
            $lifetime = $data['timestamp'] - $deviceInfo['timestamp'];
            if ($lifetime < 120) {
                $data['heartbeat_interval'] = $lifetime;
            }

            $up_condition = [];
            $up_condition['device_uuid'] = $DeviceUUID;

            $deviceObj->update($data, $up_condition);
            $infoObj->update($info, ['devid' => $deviceInfo['id']]);

            return $this->writeJsonDev($retArray);
        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
        }
    }
}